package org.x.chat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.x.chat.dto.MessageDTO;
import org.x.chat.vo.CustomMessage;
import java.security.Principal;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;

@Controller
public class ChatController {

    @Autowired
    SimpMessagingTemplate messagingTemplate;

    // 处理发送到/app/chat的消息并广播
    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public String handleMessage(String content) {
        return "【服务器转发】: " + content + " | " + new Date();
    }

    //私聊 /app/chat/user/123
    //
//私聊消息处理
    @MessageMapping("/chat/user/{toUserId}")
    public void handlePrivateMessage(
            @DestinationVariable String toUserId,
            @RequestBody MessageDTO content,
            Principal principal
    ) {

        CustomMessage customMessage = new CustomMessage();
        customMessage.setFrom(principal.getName());
        customMessage.setTo(toUserId);
        customMessage.setContent(content.getContent());
        customMessage.setType("private");
        customMessage.setTimestamp(Instant.now().toString());
        customMessage.setMessageId(UUID.randomUUID().toString());

        messagingTemplate.convertAndSendToUser(toUserId,"/queue/private", customMessage);

    }

    //群聊
    @MessageMapping("/chat/group/{groupId}")
    @SendToUser("/queue/private/reply")//回执用，通知自己
    public String handleGroupMessage(
            @DestinationVariable String groupId,
            @RequestBody MessageDTO content,
            Principal principal
    ) {
        CustomMessage customMessage = new CustomMessage();
        customMessage.setFrom(principal.getName());
        customMessage.setTo(groupId);
        customMessage.setContent(content.getContent());
        customMessage.setType("group");
        customMessage.setTimestamp(Instant.now().toString());
        customMessage.setMessageId(UUID.randomUUID().toString());
        messagingTemplate.convertAndSend("/group/group/"+groupId, customMessage);

        return "【服务器转发】: " + content + " | " + new Date();
    }
}